const app = getApp();
const utils = require('../../../utils/util.js');
import getUserCard from "../../utils/getUserCard.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navTitleText: '',
    CurrentPage: 1,
    loadingMore: 1,
    loadingMoreHidden: true,
    latitude: 0,
    longitude: 0,
    list: [],
    isShowBroPrice: false,
    cardUid: 0,
    showmenu: false,
    msgLength: 0,
    discount: 0.4,
    navBarHeight: 44,
    loginCode: ''
  },

  toAddProduct: function () {
    let that = this;
    let staffid = wx.getStorageSync('cardId');
    let url = '/pages/h5page/index?url=serviceAgreement.html';
    if (staffid) {
      wx.request({
        url: app.globalData.host + '/api/staff/GetStaffExtend?staffid=' + staffid + '&keyword=29',
        success: function (res) {
          if (res.data.Data) {
            // 已经签了合同并且上传营业执照
            url = '../addProduct/index?title=项目&seltoid=' + that.data.cardUid;
            wx.navigateTo({
              url: url,
            })
          } else {
            wx.navigateTo({
              url: url,
            })
          }
        }
      })
    }
  },

  //地图导航
  openMapLocation: function (e) {
    let Latitude = e.currentTarget.dataset.latitute;
    let Longitude = e.currentTarget.dataset.longitude;
    let Company = e.currentTarget.dataset.company;
    wx.showModal({
      title: '提示',
      content: '是否打开地图导航',
      success: function (res) {
        if (res.confirm) {
          wx.openLocation({
            latitude: Latitude,
            longitude: Longitude,
            scale: 28,
            name: "点击右边打开地图导航",
            address: Company
          })
        }
      }
    })
  },
  tabbareventListener: function (e) {
    this.setData({
      navTitleText: '云加盟'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.setData({
      navBarHeight: app.globalData.navBarHeight
    })
    if (options.id) {
      wx.setStorageSync('cardId', options.id);
    }
    that.getBrokePriceDiscount();
    that.getLocation();
    let showIndex = wx.getStorageSync('showIndex');
    if (showIndex == '/merchant/merchants/join/index') {
      wx.login({
        success: (res) => {
          that.setData({
            loginCode: res.code
          })
        },
      })
      that.setData({showmenu: true})
    }
  },

  getBrokePriceDiscount: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/distributor/getcoupondiscount?storeid=' + app.globalData.storeId,
      success: function (res) {
        let discount = 0.4;
        if (res.data.Data) {
          discount = res.data.Data.ShareDiscount / 100;
        }
        that.data.discount = discount;
      }
    })
  },


  // 看直播
  toLookLive: function (e) {
    let that = this;
    let roomid = e.currentTarget.dataset.roomid;
    let userid = e.currentTarget.dataset.seltoid;
    getUserCard(userid, function (cardid) {
      wx.navigateTo({
        url: 'plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=' + roomid + '&custom_params=' + encodeURIComponent(JSON.stringify({
          cardId: cardid,
          saleUid: that.data.cardUid
        })),
      })
    })
  },

  getInfo: function () {
    let that = this;
    let isShowBroPrice = false;
    let cardid = wx.getStorageSync('cardId');
    let uid = app.globalData.userInfo.Uid;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardid,
      success: function (res) {
        let cardUid = res.data.Data.Uid;
        if (res.data.Data.Uid == app.globalData.userInfo.Uid) {//自己的名片
          isShowBroPrice = true;
        }
        utils.getMsgUnRead(cardUid, function (msgLength) {
          that.setData({
            msgLength: msgLength
          })
        })
        let pageSize = 5;
        wx.request({
          url: app.globalData.host + '/api/Product/GetJoinList',
          data: {
            uid: uid,
            latitude: that.data.latitude,
            longitude: that.data.longitude,
            page: that.data.CurrentPage,
            pageSize: pageSize
          },
          method: 'POST',
          success: function (res) {
            that.setData({
              loadingMoreHidden: false
            })
            if (res.data.Code == 0) {
              let list = res.data.Data.Items;
              if (list && list.length > 0) {
                for (let i = 0; i < list.length; i++) {
                  list[i].status = '抢购中';
                  list[i].showProduct = true;

                  if (list[i].State == 1) {//已下架
                    list[i].status = '已下架';
                    if (isShowBroPrice && list[i].AddUid == cardUid) {//自己的产品且在自己的名片
                      list[i].showProduct = true;
                    } else {
                      list[i].showProduct = false;
                    }
                  }
                  if (list[i].State == 3) {
                    list[i].status = '已拒绝';
                    if (isShowBroPrice && list[i].AddUid == cardUid) {//自己的产品且在自己的名片
                      list[i].showProduct = true;
                    } else {
                      list[i].showProduct = false;
                    }
                  }
                  if (list[i].State == 4) {
                    list[i].status = '审核中';
                    if (isShowBroPrice && list[i].AddUid == cardUid) {//自己的产品且在自己的名片
                      list[i].showProduct = true;
                    } else {
                      list[i].showProduct = false;
                    }
                  }
                  if (list[i].ShowImg.indexOf('ps') != -1) {
                    list[i].ShowImg = utils.formatAvaterByProHead(list[i].ShowImg);
                  } else {
                    list[i].ShowImg = utils.formatAvater(list[i].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
                  }

                  list[i].extend.Avater = utils.formatAvater(list[i].extend.Avater, 'https://static.711688.net.cn/upload/card/source/');

                  if (list[i].extend.Distance >= 1000) {
                    list[i].extend.Distances = parseFloat(list[i].extend.Distance / 1000).toFixed(2);
                  }
                  list[i].extend.BrokeragePriceDiscount = parseFloat(list[i].extend.BrokeragePrice * that.data.discount).toFixed(2);

                  if (list[i].State == 0) {
                    list[i].status = '抢购中';
                    let nowTime = new Date();
                    if (list[i].extend.SendEndTime) {
                      let newTime = list[i].extend.SendEndTime;
                      newTime = new Date(Date.parse(newTime.replace(/-/g, "/")));
                      if (nowTime > newTime) {
                        list[i].status = '已售罄';
                      }
                    }
                    if (list[i].StockNumber < 1) {
                      list[i].status = '已售罄';
                    }

                    list[i].hasLive = false;
                    if (list[i].Live) {
                      // 101: 直播中, 102: 未开始, 103: 已结束, 104: 禁播, 105: 暂停中, 106: 异常，107：已过期 
                      if (list[i].Live.LiveStatus == 101) {
                        list[i].status = '正在直播';
                        list[i].hasLive = true;
                      }
                      if (list[i].Live.LiveStatus == 102) {
                        list[i].status = '即将直播';
                        list[i].hasLive = true;
                      }
                      if (list[i].Live.LiveStatus == 103) {
                        list[i].status = '直播回放';
                        list[i].hasLive = true;
                      }
                    }
                  }
                }
              }
              that.setData({
                list: list,
                loadingMore: res.data.Data.TotalPages
              })
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.Message,
                showCancel: false
              })
            }
          },
        })
        that.setData({
          isShowBroPrice: isShowBroPrice,
          cardUid: cardUid
        })
      }
    })
  },
  // 获取更多玖玖列表商品(第二页及之后)
  getMoreNearbyProductList: function () {
    let that = this;
    let uid = app.globalData.userInfo.Uid;
    let isShowBroPrice = that.data.isShowBroPrice;
    wx.request({
      url: app.globalData.host + '/api/Product/GetJoinList',
      data: {
        uid: uid,
        latitude: that.data.latitude,
        longitude: that.data.longitude,
        page: that.data.CurrentPage,
        pageSize: 5
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          let list = res.data.Data.Items;
          let preList = that.data.list;
          let newList = [];
          for (let i = 0; i < list.length; i++) {
            if (list[i].AddUid != app.globalData.userInfo.Uid) {//第二页开始过滤自己的产品
              newList.push(list[i]);
            }
          }
          list = preList.concat(newList);
          for (let i = 0; i < list.length; i++) {
            list[i].status = '抢购中';
            list[i].showProduct = true;

            if (list[i].State == 1) {//已下架
              list[i].status = '已下架';
              if (isShowBroPrice && list[i].AddUid == that.data.cardUid) {//自己的产品且在自己的名片
                list[i].showProduct = true;
              } else {
                list[i].showProduct = false;
              }
            }
            if (list[i].State == 3) {
              list[i].status = '已拒绝';
              if (isShowBroPrice && list[i].AddUid == that.data.cardUid) {//自己的产品且在自己的名片
                list[i].showProduct = true;
              } else {
                list[i].showProduct = false;
              }
            }
            if (list[i].State == 4) {
              list[i].status = '审核中';
              if (isShowBroPrice && list[i].AddUid == that.data.cardUid) {//自己的产品且在自己的名片
                list[i].showProduct = true;
              } else {
                list[i].showProduct = false;
              }
            }
            if (list[i].ShowImg.indexOf('ps') != -1) {
              list[i].ShowImg = utils.formatAvaterByProHead(list[i].ShowImg);
            } else {
              list[i].ShowImg = utils.formatAvater(list[i].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
            }

            list[i].extend.Avater = utils.formatAvater(list[i].extend.Avater, 'https://static.711688.net.cn/upload/card/source/');

            if (list[i].extend.Distance >= 1000) {
              list[i].extend.Distances = parseFloat(list[i].extend.Distance / 1000).toFixed(2);
            }
            list[i].extend.BrokeragePriceDiscount = parseFloat(list[i].extend.BrokeragePrice * that.data.discount).toFixed(2);

            if (list[i].State == 0) {
              list[i].status = '抢购中';
              let nowTime = new Date();
              if (list[i].extend.SendEndTime) {
                let newTime = list[i].extend.SendEndTime;
                newTime = new Date(Date.parse(newTime.replace(/-/g, "/")));
                if (nowTime > newTime) {
                  list[i].status = '已售罄';
                }
              }
              if (list[i].StockNumber < 1) {
                list[i].status = '已售罄';
              }

              list[i].hasLive = false;
              if (list[i].Live) {
                // 101: 直播中, 102: 未开始, 103: 已结束, 104: 禁播, 105: 暂停中, 106: 异常，107：已过期 
                if (list[i].Live.LiveStatus == 101) {
                  list[i].status = '正在直播';
                  list[i].hasLive = true;
                }
                if (list[i].Live.LiveStatus == 102) {
                  list[i].status = '即将直播';
                  list[i].hasLive = true;
                }
                if (list[i].Live.LiveStatus == 103) {
                  list[i].status = '直播回放';
                  list[i].hasLive = true;
                }
              }
            }
          }
          that.setData({
            list: list,
            loadingMore: res.data.Data.TotalPages
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      },
    })
  },
  // 加载更多
  loadMoreProduct: function () {
    var that = this;
    if (that.data.loadingMore > 1 && that.data.CurrentPage < that.data.loadingMore) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      that.getMoreNearbyProductList();
    } else {
      return
    }
  },

   // 获取地理位置  
   getLocation: function () {
    let that = this;
    utils.getLocation((location)=>{
     that.data.latitude = location.lat;
     that.data.longitude = location.lng;
     that.getInfo();
    },app);   
  },
  
  toStaffDetail: function (e) {
    let userid = e.currentTarget.dataset.cardid;
    getUserCard(userid, function (cardId) {
      wx.reLaunch({
        url: '/pages/home/index?id=' + cardId,
      })
    })
  },
  toProDetail: function (e) {
    let pid = e.currentTarget.dataset.pid;
    let seltoid = e.currentTarget.dataset.seltoid;
    let staffid = e.currentTarget.dataset.staffid;
    wx.navigateTo({
      url: '/pages/productDetails/index?saleUid=' + this.data.cardUid + '&pid=' + pid + '&seltoid=' + seltoid + '&jump=1&proStaffid=' + staffid,
    })
  },
  // 编辑带佣金的代金券
  toEditor: function (e) {
    let pid = e.currentTarget.dataset.pid;
    let seltoid = e.currentTarget.dataset.seltoid;
    wx.navigateTo({
      url: '../addProduct/index?pid=' + pid + '&seltoid=' + seltoid,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMoreProduct();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    let that = this;
    var cardid = wx.getStorageSync("cardId");
    let path = '/merchant/merchants/join/index?id=' + cardid + '&source=2';
    if (e.from === 'button') {
      let pid = e.target.dataset.pid;
      let name = e.target.dataset.name;
      let showimg = e.target.dataset.showimg;
      let seltoid = e.target.dataset.seltoid;
      path = '/pages/index/index?id=' + cardid + '&source=2' + '&pid=' + pid + '&saleUid=' + that.data.cardUid + '&seltoid=' + seltoid;
      return {
        title: name,
        imageUrl: showimg,
        path: path,
        success: function () {
          wx.showModal({
            title: '提示',
            content: '转发成功',
            showCancel: false
          })
        }
      }
    } else {
      return {
        path: path,
        success: function () {
          wx.showModal({
            title: '提示',
            content: '转发成功',
            showCancel: false
          })
        }
      }
    }
  }
})